package com.itany.corejava.day17;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;

//通过Class对象访问类里的信息
public class TestClass3 {


    public static void main(String[] args) throws Exception {


        Class c=Person.class;



        //调用无参构造方法创建对象
        Person p1= (Person) c.newInstance();
        System.out.println(p1);

        //调用有参构造方法创建对象
        Constructor constructor=c.getDeclaredConstructor(String.class,int.class,boolean.class);
        Person p2= (Person) constructor.newInstance("abc",12,false);
        System.out.println(p2);
        System.out.println(p2.getName());


        //访问属性
        String fieldName="name";
        Field nameField=c.getDeclaredField(fieldName);
        nameField.setAccessible(true);
        System.out.println(nameField.get(p2));
        nameField.set(p1,"aaa");
        System.out.println(p1.getName());



        //访问方法
        Method sleepMethod=c.getDeclaredMethod("sleep");
        sleepMethod.invoke(p1);

//        Method eatMethod=c.getDeclaredMethod("eat");
//        eatMethod.invoke(p2);

        Method eatMethod=c.getDeclaredMethod("eat",String.class);
        eatMethod.invoke(p2,"肉");


        Method countMethod=c.getDeclaredMethod("getCount");
        int count= (int) countMethod.invoke(null);
        System.out.println(count);


        p1.setName("abc");

    }
























}
